package edu.thu.thss.yxy.audionotifier;

import java.applet.Applet;
import java.applet.AudioClip;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import edu.thu.thss.yxy.util.PropertiesUtil;

public class AlertManager {
	public static final String INCOMING_MESSAGE = "sounds/incomingMessage.wav";
	public static final String INCOMING_FILE = "sounds/incomingMessage.wav";
	public static final String INCOMING_CALL = "sounds/incomingCall.wav";
	public static final String OUTGOING_CALL = "sounds/ring.wav";

	public static final String DIAL_ZERO = "sounds/one_1.wav";
	public static final String DIAL_ONE = "sounds/one_1.wav";
	public static final String DIAL_TWO = "sounds/two_2.wav";
	public static final String DIAL_THREE = "sounds/three_3.wav";
	public static final String DIAL_FOUR = "sounds/four_4.wav";
	public static final String DIAL_FIVE = "sounds/five_5.wav";
	public static final String DIAL_SIX = "sounds/six_6.wav";
	public static final String DIAL_SEVEN = "sounds/seven_7.wav";
	public static final String DIAL_EIGHT = "sounds/eight_8.wav";
	public static final String DIAL_NINE = "sounds/nine_9.wav";
	public static final String DIAL_DIEZ = "sounds/one_1.wav";
	public static final String DIAL_STAR = "sounds/one_1.wav";
	public static final String BUSY = "sounds/busy.wav";
	public static final String DIAL = "sounds/dial.wav";
	public static final String ALERTING = "sounds/alerting.wav";
	public static final String RINGING = "sounds/ringing.wav";

	private static final Map<String, AudioClip> audioClips = new HashMap<String, AudioClip>();

	public static void startAlert(String alertResourceName) {
		AudioClip alertClip = getAlertClip(alertResourceName, true);
		if (alertClip == null) {
			return;
		}

		String loop = PropertiesUtil
				.getProperty("edu.thu.thss.yxy.gui.LOOP_SOUND_ALERTS");
		if (loop != null && loop.trim().equals("false")) {
			alertClip.play();
		} else {
			alertClip.loop();
		}
	}

	public static void stopAllAlerts() {
		Set<String> alertClipsEnum = audioClips.keySet();
		for (String alert : alertClipsEnum) {
			stopAlert(alert);
		}
	}

	public static void stopAlert(String alertResourceName) {
		AudioClip alertClip = getAlertClip(alertResourceName, false);
		if (alertClip != null) {
			alertClip.stop();
		}
	}

	public static AudioClip getAlertClip(String alertResourceName,
			boolean create) {
		AudioClip clip = (AudioClip) audioClips.get(alertResourceName);
		if (clip == null && create) {
			clip = Applet.newAudioClip(PropertiesUtil
					.getResource(alertResourceName));
			if (clip != null) {
				audioClips.put(alertResourceName, clip);
			}
		}
		return clip;
	}
}
